<?php
/**
 * Author: DRERY <rui1642@foxmail.com>
 */
namespace backend\components;

use yii\base\Object;

class ExcelWriter extends Object
{
    /**
     * @var \PHPExcel
     */
    private $objPHPExcel;

    public $filePath;

    public $fileType;

    public $isFirsted = array();

    public $curSheet = 0;

    public $filename;

    public function init()
    {
        $this->objPHPExcel = new \PHPExcel ();
        $this->objPHPExcel->getProperties()->setCreator("Drery")->setLastModifiedBy("Drery");
    }

    public function getPHPExcel()
    {
        return $this->objPHPExcel;
    }

    public function title($title)
    {
        $this->objPHPExcel->getProperties()->setTitle($title)->setSubject($title);
        return $this;
    }

    public function sheet($sheet = 0)
    {
        $this->objPHPExcel->setActiveSheetIndex($sheet);
        $this->curSheet = $sheet;
        return $this;
    }

    public function create()
    {
        $this->objPHPExcel->createSheet();
        return $this;
    }

    public function path($filePath)
    {
        $this->filePath = $filePath;
        return $this;
    }

    public function sheetName($name)
    {
        $this->objPHPExcel->getActiveSheet()->setTitle($name);
        return $this;
    }

    public function columnListValidation($columnIndex, $list, $options = [])
    {
        $column = \PHPExcel_Cell::stringFromColumnIndex($columnIndex);
        $coordinate = '$'.$column.':'.'$'.$column;
        return $this->listValidation($coordinate, $list, $options = []);
    }

    public function listValidation($coordinate, $list, $options = [])
    {
        $validation = new \PHPExcel_Cell_DataValidation();
        $validation->setType( \PHPExcel_Cell_DataValidation::TYPE_LIST );
        isset($options['errorStyle']) ? $validation->setErrorStyle($options['errorStyle']) : $validation->setErrorStyle(\PHPExcel_Cell_DataValidation::STYLE_STOP);
        isset($options['allowBlank']) ? $validation->setAllowBlank($options['allowBlank']) : $validation->setAllowBlank(false);
        isset($options['showInputMessage']) ? $validation->setShowInputMessage($options['showInputMessage']) : $validation->setShowInputMessage(true);
        isset($options['showErrorMessage']) ? $validation->setShowErrorMessage($options['showErrorMessage']) : $validation->setShowErrorMessage(true);
        isset($options['showDropDown']) ? $validation->setShowDropDown($options['showDropDown']) : $validation->setShowDropDown(true);
        isset($options['errorTitle']) ? $validation->setErrorTitle('errorTitle') : $validation->setErrorTitle('输入的值有误');
        isset($options['error']) ? $validation->setError('error') : $validation->setError('您输入的值不在下拉框列表内');
        isset($options['prompTitle']) && $validation->setPromptTitle('prompTitle');
        isset($options['prompt']) && $validation->setPrompt('prompt');
        if (is_array($list))
            $list = join(',', $list);
        if (substr($list, 0, 1) != '=')
            $list = '"' . $list . '"';
        $validation->setFormula1($list);
        $this->objPHPExcel->getActiveSheet()->setDataValidation($coordinate, $validation);
        return $this;
    }

    public function listValidate()
    {
        $validation = new \PHPExcel_Cell_DataValidation();
        $validation->setType( \PHPExcel_Cell_DataValidation::TYPE_LIST );
        $validation->setErrorStyle( \PHPExcel_Cell_DataValidation::STYLE_INFORMATION );
        $validation->setAllowBlank(false);
        $validation->setShowInputMessage(true);
        $validation->setShowErrorMessage(true);
        $validation->setShowDropDown(true);
        $validation->setErrorTitle('Input error');
        $validation->setError('Value is not in list.');
        $validation->setPromptTitle('Pick from list');
        $validation->setPrompt('Please pick a value from the drop-down list.');
        $validation->setFormula1('"Item A,Item B,Item C"');
        $this->objPHPExcel->getActiveSheet()->setDataValidation('$A:$A', $validation);
        return $this;
    }

    public function first($array)
    {
        for ($k = 0, $c = 'A'; $k < count($array); $k++, $c++) {
            $this->objPHPExcel->getActiveSheet()->setCellValue($c . '1', $array [$k]);
        }
        $this->isFirsted [$this->curSheet] = 1;
        return $this;
    }

    public function content($list, $fields)
    {
        if (!empty($this->isFirsted [$this->curSheet])) {
            $r = 2;
        } else {
            $r = 1;
        }
        foreach ($list as $item) {
            for ($k = 0, $c = 'A'; $k < count($fields); $k++, $c++) {
                $content = !isset($item[$fields[$k]]) ? '' : (string)$item [$fields [$k]];
                $this->objPHPExcel->getActiveSheet()->setCellValueExplicit($c . $r, $content, \PHPExcel_Cell_DataType::TYPE_STRING);
            }
            $r++;
        }
        return $this;
    }

    public function type($type = 'Excel2007')
    {
        $this->fileType = $type;
        return $this;
    }

    /**
     * @param $filename
     * @return $this
     */
    public function name($filename)
    {
        $this->filename = $filename;
        return $this;
    }

    public function save($down = false)
    {
        if (!$type = $this->fileType)
            $type = 'Excel2007';
        if ($down) {
            $pFilename = 'php://output';
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $this->filename . '"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
        } else {
            $pFilename = $this->filePath;
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($this->objPHPExcel, $type);
        return $objWriter->save($pFilename);
    }
}